package autoorder.zsxmlv.service;

import autoorder.zsxmlv.mapper.GoodsMapper;
import autoorder.zsxmlv.mapper.ShopMapper;
import autoorder.zsxmlv.po.Account;
import autoorder.zsxmlv.po.Goods;
import autoorder.zsxmlv.po.Shop;
import autoorder.zsxmlv.vo.GoodsVo;
import common.zsxmlv.enums.ResultEnum;
import common.zsxmlv.utils.PropertiesUtil;
import common.zsxmlv.utils.ResultUtil;
import common.zsxmlv.vo.Result;
import common.zsxmlv.vo.Table;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: ZSXM
 * @Description:
 * @Company: DingZheng
 * @Date: Create by 2018/6/2 22:23
 * @Version: 1.0
 * @Modify by:
 */
@Service
@Transactional
public class GoodsService {

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private ShopMapper shopMapper;

    public static Integer add = 0, update = 0;

    public Goods getGoodsById(Integer id) {
        return goodsMapper.selectByPrimaryKey(id);
    }

    /**
     * 批量更新商品状态
     * @param ids 商品id的集合,以“,”分隔
     * @param type 0在售 1下架
     * @return
     */
    public Result updateGoodsStatus(String ids,Integer type) {
        Result result = new Result();
        if (ids == null || "".equals(ids)) {
            result.setSuccess(false);
            result.setMsg(ResultEnum.PARAM_ERROR.getMsg());
            result.setCode(ResultEnum.PARAM_ERROR.getCode());
        } else {
            try {
                int index = ids.indexOf(",");
                if (index >= 0) {
                    String[] split = ids.split(",");
                    for (String id : split) {
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("id", id);
                        map.put("status", type);
                        goodsMapper.updateGoodsStatus(map);
                    }
                } else {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("id", ids);
                    map.put("status", type);
                    goodsMapper.updateGoodsStatus(map);
                }
                result.setSuccess(true);
                result.setMsg(ResultEnum.UPDATE_SUCCESS.getMsg());
                result.setCode(ResultEnum.UPDATE_SUCCESS.getCode());
            } catch (Exception e) {
                result.setSuccess(false);
                result.setMsg("更新失败");
            }
        }
        return result;
    }

    /**
     * update goods status by goodsId
     * @param goodsId goodsId
     * @return result
     */
    public Result updateGoodsStatusByGoodsId(String goodsId){
        Result result = new Result();
        if (goodsId != null && !"".equals(goodsId)) {
            Goods goods = goodsMapper.selectByGoodsId(goodsId);
            if (goods != null) {
                Integer status = goods.getStatus();
                status = status == 0 ? 1 : 0;
                goods.setStatus(status);
                int i = goodsMapper.updateByPrimaryKey(goods);
                if (i > 0) {
                    result.setSuccess(true);
                    result.setMsg(ResultEnum.UPDATE_SUCCESS.getMsg());
                } else {
                    result.setSuccess(false);
                    result.setMsg(ResultEnum.UPDATE_ERROR.getMsg());
                }
            } else {
                result.setSuccess(false);
                result.setMsg(ResultEnum.NOT_FOUND_UPDATE_ERROR.getMsg());
            }
        } else {
            result.setSuccess(false);
            result.setMsg(ResultEnum.PARAM_ERROR.getMsg());
        }
        return result;
    }

    /**
     * select page by goodsName and status and page and limit
     * @param page pageNumber
     * @param limit pageSize
     * @param goodsName like goodsName
     * @param status status
     * @return table
     */
    public Table selectByPage(Integer page,Integer limit, String goodsName, Integer status, Integer shopId){
        Table table = new Table();
        boolean condition = page != null && page != 0 && limit != null && limit != 0;
        if (condition){
            HashMap<Object, Object> map = new HashMap<>();
            map.put("startRecord", (page - 1) * limit);
            map.put("pageSize", limit);
            map.put("goodsName", goodsName);
            map.put("status", status);
            map.put("shopId", shopId);
            List<GoodsVo> goods = goodsMapper.selectByPage(map);
            int count = goodsMapper.selectByCount(map);
            table = ResultUtil.getResultTableByPageLimit(goods, count);
        }else {
            table.setMsg(ResultEnum.PARAM_ERROR.getMsg());
            table.setCode(ResultEnum.PARAM_ERROR.getCode());
        }
        return table;
    }

    /**
     * 执行获取商品数据&&更新现有商品数据状态
     * @return result
     */
    public Result getGoodsListByNetwork(Integer shopId){
        try {
            Result result = new Result();
            if (shopId == null || shopId == 0) {
                result.setCode(ResultEnum.PARAM_ERROR.getCode());
                result.setSuccess(false);
                result.setMsg(ResultEnum.PARAM_ERROR.getMsg());
            } else {
                Shop shop = shopMapper.selectByPrimaryKey(shopId);
                String url = shop.getUrl();
                Document document = Jsoup.connect(url).get();
                Elements youhui = document.getElementsByClass("youhui");
                ArrayList<Goods> goodsArrayList = null;
                if (youhui.size() > 0) {
                    goodsArrayList = new ArrayList<>();
                    int i1 = goodsMapper.deleteByShopId(shopId);
                    System.out.println("删除店铺id为" + shopId + "的所有商品");
                    for (Element e : youhui) {
                        Goods goods = new Goods();
                        goods.setGoodsId(e.getElementsByClass("productId").attr("value"));
                        goods.setGoodsName(e.select("li").first().select("img").attr("alt"));
                        goods.setGoodsPic(e.select("li").first().select("img").attr("src"));
                        // 商品价格 设置0 不显示
//                        String cost = e.getElementsByClass("cost").text().substring(1);
//                        float price  = Float.parseFloat(cost);
                        BigDecimal bigDecimal = BigDecimal.valueOf(0);
                        goods.setGoodsPrice(bigDecimal);
                        goods.setShopId(shopId);
                        goodsArrayList.add(goods);
                    }
                    int i2 = goodsMapper.insertByBatch(goodsArrayList);
                    if (i2 > 0){
                        result.setSuccess(true);
                        result.setMsg("商品更新成功！");
                    }else {
                        result.setSuccess(false);
                        result.setMsg("商品更新失败！");
                    }
                } else {
                    result.setSuccess(false);
                    result.setMsg("没有找到商品数据");
                }
            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("获取商品数据异常");
        }
        return null;
    }


    /**
     * 根据商品状态获取所有商品
     * @param status 商品是否上架 (0上架  1下架)
     * @return
     */
    public List<Goods> listAllGoodsByStatus(Integer status) {
        List<Goods> goods = goodsMapper.listAllGoodsByStatus(status);
        return goods;
    }

}
